package cn.wolfcode.shop.cloud.common;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by wolfcode-lanxw
 */
public class CookieUtils {

    public static final String USER_IN_TOKEN = "userToken";
    public static final String DEFAULT_DOMAIN = "localhost";
    public static final String DEFAULT_PATH = "/";
    public static final int DEFAULT_MAX_AGE = 1800;

    /**
     * 添加token到响应头
     * @param token
     * @param resp
     */
    public static void addToken(String token, HttpServletResponse resp) {
        Cookie cookie = new Cookie(USER_IN_TOKEN, token);
        cookie.setDomain(DEFAULT_DOMAIN);
        cookie.setPath(DEFAULT_PATH);
        cookie.setMaxAge(DEFAULT_MAX_AGE);
        resp.addCookie(cookie);
    }

    /**
     * 从请求头中获取token
     * @param req
     * @return
     */
    public static String getToken(HttpServletRequest req) {
        if (req == null) {
            return null;
        }

        Cookie[] cookies = req.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (USER_IN_TOKEN.equals(cookie.getName())) {
                    return cookie.getValue();
                }
            }
        }

        return null;
    }
}
